package com.findviewbydream.evil.helloyouth.Fragment.HomeFragmentContent;

import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.findviewbydream.evil.helloyouth.Bean.SecondHandItemBean;
import com.findviewbydream.evil.helloyouth.Data.NetData;
import com.findviewbydream.evil.helloyouth.Data.UserData;
import com.findviewbydream.evil.helloyouth.MainActivityUtils.MainActivityUtils;
import com.findviewbydream.evil.helloyouth.R;
import com.findviewbydream.evil.helloyouth.Utils.SLog;
import com.findviewbydream.evil.helloyouth.Utils.SToast;
import com.findviewbydream.evil.helloyouth.Utils.SuperToast.ButtonToast;
import com.findviewbydream.evil.helloyouth.Utils.SuperToast.OnClick;
import com.findviewbydream.evil.helloyouth.Utils.SuperToast.SuperToast;
import com.findviewbydream.evil.helloyouth.View.LoadingGif.LoadingDrawable;
import com.findviewbydream.evil.helloyouth.View.LoadingGif.SwapLoadingRenderer;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.lang.reflect.Type;
import java.util.ArrayList;

import cn.iwgang.familiarrecyclerview.FamiliarRecyclerView;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import okhttp3.Call;

/********************************************
 * 工程名：HelloYouth
 * 包名：com.findviewbydream.evil.helloyouth.Fragment
 * 时间：16-6-7 下午11:29
 * 作者：白雨濃 evil
 * 邮箱：evilbai@foxmail.com
 * 内容：二手市场界面
 ********************************************/
public class SecondHandFragment extends Fragment
{
    private View view;
    private static SecondHandFragment secondHandFragment;


    /*RecyclerView*/
    private FamiliarRecyclerView recyclerView;
    private Adapter adapter;
    private ArrayList<SecondHandItemBean> list;

    /*下拉刷新*/
    private PtrFrameLayout ptrFrameLayout;/*下拉刷新主控件*/
    private LoadingDrawable loadingDrawable;/*下拉刷新的加载动画*/

    /**
     * 入口函数
     */
    public static SecondHandFragment newInstance()
    {
        if (secondHandFragment == null)
            secondHandFragment = new SecondHandFragment();
        return secondHandFragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
    {
        view = inflater.inflate(R.layout.home_secondhandfragment, container, false);

        initView(view);/*初始化控件*/
        setRecyclerView();/*设置RecyclerView*/
        setPtrFrameLayout();/*设置下拉刷新*/

        toNetWork();/*初始化加载*/
        onClick();/*点击事件*/

        return view;
    }

    /**
     * 初始化控件
     *
     * @param view
     */
    private void initView(View view)
    {
        recyclerView = (FamiliarRecyclerView) view.findViewById(R.id.recyclerView);
        ptrFrameLayout = (PtrFrameLayout) view.findViewById(R.id.ptrFrameLayout);
    }

    private void toNetWork()
    {
        String id = "0";
        if (list.size() != 0)
            id = list.get(0).getId();
        SLog.print("id=" + id);
        MainActivityUtils.startLoading();
        OkHttpUtils.post()
                .url(NetData.IP + "SecondHandItem")
                .addParams("type", "QUERYLIST")
                .addParams("IMEI", UserData.IMEI)
                .addParams("lastId", id)
                .build()
                .execute(new StringCallback()
                {
                    ItemList itemList;

                    @Override
                    public void onError(Call call, Exception e, int id)
                    {
                        stopRefresh();
                        MainActivityUtils.stopLoading();
                        SuperToast.buttonToast(getActivity()).setText("加载失败")
                                .setBackgroundColor(ButtonToast.Background.ORANGE).show();
                    }

                    @Override
                    public void onResponse(String response, int id)
                    {
                        stopRefresh();
                        MainActivityUtils.stopLoading();
                        /*解析JSON*/
                        {
                            Type type = new TypeToken<ItemList>()
                            {
                            }.getType();

                            itemList = new Gson().fromJson(response, type);
                        }
                        /*添加数据*/
                        {
                            if (itemList.IMEI.equals(UserData.IMEI))
                            {
                                if (list != null)
                                {
                                    if (itemList.size == 0)
                                        SuperToast.buttonToast(getActivity()).setText("暂时没有新的商品了哦，一会再试试吧！").show();
                                    else
                                        new Thread(new Runnable()
                                        {
                                            @Override
                                            public void run()
                                            {
                                                for (int i = 0; i < itemList.size; i++)
                                                {
                                                    list.add(0, itemList.list.get(i));
                                                }
                                                handler.sendEmptyMessage(0);
                                            }
                                        }).start();
                                }
                            }
                            else
                                SuperToast.buttonToast(getActivity()).setText("内部错误，请重新加载")
                                        .setButtonIcon(ButtonToast.DarkIcon.刷新).setOnClick(new OnClick()
                                {
                                    @Override
                                    public void onClick(View view, Parcelable token)
                                    {
                                        toNetWork();
                                    }
                                }).show();
                        }
                    }

                    /**
                     * 置换数组，放入线程
                     */
                    private Handler handler = new Handler()
                    {
                        @Override
                        public void handleMessage(Message msg)
                        {
                            super.handleMessage(msg);
                            adapter.notifyDataSetChanged();/*调用刷新*/
                        }
                    };

                    /**
                     * 停止刷新
                     */
                    private void stopRefresh()
                    {
                        if (ptrFrameLayout != null)
                            ptrFrameLayout.refreshComplete();
                        if (loadingDrawable != null)
                            loadingDrawable.stop();
                    }
                });
    }


    /**
     * 设置RecyclerView
     */
    private void setRecyclerView()
    {
        list = new ArrayList<>();
        adapter = new Adapter();
        recyclerView.setAdapter(adapter);
    }


    /**
     * 设置下拉刷新
     */
    private void setPtrFrameLayout()
    {
        final View header = LayoutInflater.from(getContext()).inflate(R.layout.refresh_header, null);
        final ImageView imageView = (ImageView) header.findViewById(R.id.refresh_header_imageView);
        loadingDrawable = new LoadingDrawable(new SwapLoadingRenderer(getContext()));

        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT
                , 150);

        header.setLayoutParams(layoutParams);

        ptrFrameLayout.setDurationToCloseHeader(1500);
        ptrFrameLayout.setHeaderView(header);
        ptrFrameLayout.setPtrHandler(new PtrHandler()
        {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header)
            {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame)
            {
                imageView.setImageDrawable(loadingDrawable);
                loadingDrawable.start();
                ptrFrameLayout.postDelayed(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        //ptrFrameLayout.refreshComplete();
                        toNetWork();
                    }
                }, 100);
            }
        });
    }

    /**
     * 点击事件
     */
    private void onClick()
    {
        recyclerView.setOnItemClickListener(new FamiliarRecyclerView.OnItemClickListener()
        {
            @Override
            public void onItemClick(FamiliarRecyclerView familiarRecyclerView, View view, int position)
            {
                if (!list.get(position).isInvalid())
                    SToast.show(getContext(), list.get(position).getId());
            }
        });
    }


    /**
     * 内部类
     * RecyclerView的适配器
     */
    private class Adapter extends RecyclerView.Adapter<ViewHolder>
    {
        SecondHandItemBean itemBean;

        @Override
        public int getItemViewType(int position)
        {
            itemBean = list.get(position);
            switch (itemBean.getType())
            {
                case SecondHandItemBean.TYPE_ONEIMG_LAYOUT:
                    return R.layout.home_fragment_item_type1;
                default:
                    return R.layout.home_fragment_item_type1;
            }
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
        {
            View view = LayoutInflater.from(getContext())
                    .inflate(viewType, parent, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position)
        {
            /*加载主要图片*/
            Glide.with(getContext()).load(itemBean.getImagePath())
                    .placeholder(R.drawable.img_fail).into(holder.imageView);
            SLog.print(itemBean.getId() + "=" + itemBean.isInvalid() + itemBean.getTag()[0]);

            /*如果失效，覆盖图片*/
            if (itemBean.isInvalid())
                holder.invalid.setVisibility(View.VISIBLE);
            else
                holder.invalid.setVisibility(View.GONE);
            /*设置标题*/
            holder.title.setText("  " + itemBean.getTitle());
            /*设置标签*/
            holder.item_tag.removeAllViews();
            holder.item_tag.addView(addTags(itemBean.getTag()));
            /*剩余数量，全部减去已售*/
            holder.surplus.setText("剩余：" + (itemBean.getTotal() - itemBean.getSold()) + "件");
            /*设置价格*/
            holder.price.setText("￥" + itemBean.getPrice() + "元");
        }

        @Override
        public int getItemCount()
        {
            return list.size();
        }

        /**
         * 动态布局添加标签
         */
        private LinearLayout addTags(String[] tags)
        {
            LinearLayout linearLayout = new LinearLayout(getContext());
            ViewGroup.LayoutParams layoutParams = new PtrFrameLayout
                    .LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT
                    , ViewGroup.LayoutParams.WRAP_CONTENT);
            linearLayout.setLayoutParams(layoutParams);
            linearLayout.setOrientation(LinearLayout.HORIZONTAL);

            for (int i = 0; i < tags.length; i++)
            {
                TextView textView = new TextView(getContext());
                LinearLayout.LayoutParams textViewParams = new LinearLayout
                        .LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT
                        , ViewGroup.LayoutParams.WRAP_CONTENT);
                textViewParams.setMargins(0, 0, 20, 0);
                textView.setLayoutParams(textViewParams);

                switch (tags[i])
                {
                    case "抢购":
                        textView.setBackgroundColor(getResources().getColor(R.color.orange));
                        break;
                    case "热销":
                        textView.setBackgroundColor(getResources().getColor(R.color.red));
                        break;
                    case "失效":
                        textView.setBackgroundColor(getResources().getColor(R.color.gray));
                        break;
                }
                textView.setText(tags[i]);
                textView.setTypeface(Typeface.SERIF);/*设置粗体*/
                textView.setTextSize(12);
                textView.setTextColor(getResources().getColor(R.color.white));
                linearLayout.addView(textView);
            }

            return linearLayout;
        }
    }

    private class ViewHolder extends RecyclerView.ViewHolder
    {
        private ImageView imageView;/*显示图片*/
        private ImageView invalid;/*失效覆盖*/
        private TextView title;/*标题*/
        private LinearLayout item_tag;/*标签布局，动态添加*/
        private TextView surplus;/*剩余数量*/
        private TextView price;/*价格*/

        public ViewHolder(View itemView)
        {
            super(itemView);
            this.imageView = (ImageView) itemView.findViewById(R.id.imageView);
            this.invalid = (ImageView) itemView.findViewById(R.id.invalid);
            this.title = (TextView) itemView.findViewById(R.id.title);
            this.item_tag = (LinearLayout) itemView.findViewById(R.id.item_tag);
            this.surplus = (TextView) itemView.findViewById(R.id.surplus);
            this.price = (TextView) itemView.findViewById(R.id.price);
        }
    }

    private class ItemList
    {
        private String IMEI;
        private int size;
        private ArrayList<SecondHandItemBean> list;
    }
}
//todo:设置TextView周边图片 必须设置大小，否则不显示
        /*Drawable drawable = getContext().getResources().getDrawable(R.mipmap.ic_launcher);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            holder.title.setCompoundDrawables(drawable, null, null, null);*/